<template>
  <div>
    <!-- 分享弹框 -->
    <el-dialog
      title="链接分享"
      v-model="dialogEnjoy"
      width="550px"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="closeDialogEnjoyClick"
    >
      <div v-if="isEnjoySuccess">
        <el-form :model="formEnjoy">
          <div style="display: flex; flex-direction: column">
            <el-form-item v-if="formEnjoy.shareForm == '1'" label="设置密码" label-width="80px">
              <div class="input-password">
                <el-input v-model="formEnjoy.password" placeholder="请输入密码" />
                <el-tooltip effect="dark" :content="tooltipPassword" placement="top">
                  <el-icon style="margin-left: 15px; font-size: 19px"><Warning /></el-icon>
                </el-tooltip>
              </div>
            </el-form-item>

            <el-form-item label="过期时间:" label-width="80px">
              <div style="display: flex; justify-content: space-between; width: 100%">
                <el-date-picker
                  v-model="formEnjoy.deadline"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @input="$forceUpdate()"
                >
                </el-date-picker>
                <div class="more_set" @click="isMoreSetDiv = !isMoreSetDiv">
                  <span>更多设置</span>
                  <el-icon v-if="isMoreSetDiv"><CaretTop /></el-icon>
                  <el-icon v-else><CaretBottom /></el-icon>
                </div>
              </div>
            </el-form-item>

            <!-- 更多设置 -->
            <div class="" v-if="isMoreSetDiv">
              <el-form-item label="操作权限:" label-width="80px">
                <div style="display: flex; align-items: center">
                  <el-checkbox-group v-model="formEnjoy.isPreview"><el-checkbox label="预览" disabled></el-checkbox></el-checkbox-group>
                  <el-checkbox-group v-model="formEnjoy.isDownload" style="margin-left: 15px">
                    <el-checkbox label="下载"> </el-checkbox>
                  </el-checkbox-group>
                  <el-tooltip effect="dark" :content="tooltipContent" placement="top" style="margin-left: 15px">
                    <el-icon style="margin-left: 15px; font-size: 19px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
              </el-form-item>

              <!-- <el-form-item label="可访问者:" label-width="80px" v-if="!isTeamPeople"> -->
              <el-form-item label="可访问者:" label-width="80px">
                <el-tag
                  style="gap: 5px"
                  :key="indext"
                  v-for="(tag, indext) in formEnjoy.accessibleArray"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag.userName ? tag.userName : tag.name }}
                </el-tag>
                <el-button class="button-new-tag" type="primary" @click="showInterviewDialogClick">选择可访问者</el-button>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <!-- 弹窗底部操作按钮 -->
        <!-- <template #footer></template> -->
        <div class="dialog-footer" style="display: flex; justify-content: flex-end">
          <el-button @click="closeDialogEnjoyClick">取 消</el-button>
          <el-button type="primary" @click="SureDialogEnjoyClick">生成链接</el-button>
        </div>
      </div>

      <div v-if="!isEnjoySuccess">
        <div class="success_link">
          <span class="success_title">提取密码:</span>
          <span>{{ successLinkObj.shareForm == '1' ? successLinkObj.password : '无' }}</span>
        </div>
        <div class="success_link">
          <span class="success_title">过期时间:</span>
          <span>{{ successLinkObj.deadline ? successLinkObj.deadline : '永久' }}</span>
        </div>
        <div class="success_link">
          <span class="success_title">操作权限:</span>
          <span>{{ successLinkObj.isPreview == 1 ? '可预览' : '' }}</span>
          <span>{{ successLinkObj.isPreview == 1 && successLinkObj.isDownload == 1 ? '/' : '' }}</span>
          <span>{{ successLinkObj.isDownload == 1 ? '可下载' : '' }}</span>
        </div>
        <div class="success_link">
          <span class="success_title">链接地址:</span>
          <span class="success_url" @click="skipRedirectClick(successLinkObj.linkAddress)">{{ successLinkObj.linkAddress }}</span>
        </div>

        <div slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end">
          <el-button @click="editHistoryLink(successLinkObj.id)">编辑链接</el-button>
          <el-button type="primary" @click="copyLink(successLinkObj.linkAddress)">复制链接</el-button>
        </div>
      </div>
    </el-dialog>

    <SelectUser ref="SelectUserRef" @sureDialogTransferClick="sureDialogTransferClick" />
  </div>
</template>

<script setup lang="ts">
import SelectUser from '@/views/components/select-user-check/select-user.vue'; // 选择人
const SelectUserRef = ref(null);
import { ApiPerfilesShareId, ApiPerEditShare } from '@/api/personDoc/personDocApi';
import { randomPassword } from '@/utils/yuUtils.js';
import useUserStore from '@/store/modules/user';

const props = defineProps({
  Refresh: {
    type: Boolean
  }
});
const userStore = useUserStore();
const { proxy } = getCurrentInstance() as any;

const isMoreSetDiv = ref(false); //更多设置

const tooltipContent = ref(
  '请确认您拥有被分享文件的权限。例如，当您没有文件下载权限时将无法开启该文件外链的下载操作功能。如有需要请联系文件管理员获取文件权限。'
);
const emit: any = defineEmits(['getTableData']);
const dialogEnjoy = ref(false);
const formEnjoy = reactive({
  shareForm: '1',
  password: '',
  deadline: '',
  isPreview: ['预览'],
  isDownload: ['下载'],
  visitsNumber: '',
  downloadsNumber: '',
  accessibleArray: [],
  remark: '',
  linkAddress: '',
  endTiem: '',
  id: '',
  name: ''
});

const successLinkObj: any = ref({
  shareForm: '1',
  password: '',
  deadline: '',
  isPreview: ['预览'] as any,
  isDownload: ['下载'] as any,
  linkAddress: '',
  id: ''
});
const isEnjoySuccess = ref(true); //分享成功之后显示链接地址页面
const isCreateOrEdit = ref(null); //创建或者编辑链接  1为创建 2为编辑

const isTeamPeople = ref('');
const tooltipPassword = ref('因为受法律限制，必须要设置密码才可以共享');

// 打开弹框
const openDialog = (val) => {
  dialogEnjoy.value = true;
  editHistoryLink(val);
};
//关闭共享
const closeDialogEnjoyClick = () => {
  dialogEnjoy.value = false;
};

// 叉掉访问者
const handleClose = (tag) => {
  formEnjoy.accessibleArray.splice(formEnjoy.accessibleArray.indexOf(tag), 1);
};

// 打开选择可访问者的dialog
const showInterviewDialogClick = () => {
  SelectUserRef.value.openDialogTransfer();

  // 如果选择了本团队的人
  //   if (isTeamPeople.value) {
  //     this.$refs.yuSelectUserNewUiRef.TeamPersonList = formEnjoy.accessibleArray;
  //     this.$refs.yuSelectUserNewUiRef.dialogTransfer = true;
  //   } else {
  //     this.$refs.yuDeptMember._data.TeamPersonList = formEnjoy.accessibleArray;
  //     this.$refs.yuDeptMember._data.dialogTransfer = true;
  //   }
};

//拿到选择的人
const sureDialogTransferClick = (val) => {
  formEnjoy.accessibleArray = val;
  SelectUserRef.value.closeDialogTransferClick();
};

// 生成链接
const SureDialogEnjoyClick = () => {
  // if (this.formEnjoy.deadline == '') {
  // 	this.$message.warning('过期时间不能为空');
  // 	return;
  // }

  console.log(isCreateOrEdit.value, '创建还是编辑');

  if (formEnjoy.shareForm == '1' && formEnjoy.password.trim().length != 4) {
    ElMessage.warning('密码不能为空,由数字+字母组成的4位密码');
    return;
  }

  if (formEnjoy.visitsNumber != '' && Number(formEnjoy.visitsNumber) <= 0) {
    ElMessage.warning('访问次数不能小于等于0,不填为无限次');
    return;
  }
  if (formEnjoy.visitsNumber != '' && Number(formEnjoy.downloadsNumber) <= 0) {
    ElMessage.warning('下载次数不能小于等于0,不填为无限次');
    return;
  }
  let accessibleId;
  // // 没有选择必须时=是本团队的人
  // if (!isTeamPeople.value) {
  //   accessibleId = formEnjoy.accessibleArray.map((item) => {
  //     return item.userId;
  //   });
  // } else {
  //   // accessibleId = this.formEnjoy.accessibleArray.map((item) => {
  //   //   return item.id;
  //   // });
  //   accessibleId = [];
  // }

  accessibleId = formEnjoy.accessibleArray.map((item) => {
    return item.userId;
  });
  // 编辑链接
  if (isCreateOrEdit.value == 2) {
    //这里是编辑链接的请求参数
    let requestData = {
      shareForm: parseInt(formEnjoy.shareForm),
      password: formEnjoy.shareForm == '1' ? formEnjoy.password : '',
      // deadline: formEnjoy.deadline ? formEnjoy.deadline.getTime() : '',
      deadline: formEnjoy.deadline ? formEnjoy.deadline : '',
      isPreview: formEnjoy.isPreview.length != 0 ? 1 : 0,
      isDownload: formEnjoy.isDownload.length != 0 ? 1 : 0,
      visitsNumber: formEnjoy.visitsNumber ? parseInt(formEnjoy.visitsNumber) : '',
      downloadsNumber: formEnjoy.downloadsNumber ? parseInt(formEnjoy.downloadsNumber) : '',
      accessibleId: accessibleId.join(','),
      remark: formEnjoy.remark,
      id: formEnjoy.id,
      name: formEnjoy.name,
      teamType: isCreateOrEdit.value
    };

    ApiPerEditShare(requestData).then((res) => {
      successLinkObj.value = res.data;
      ElMessage.success('编辑成功');
      isEnjoySuccess.value = false;
      if (props.Refresh == true) {
        emit('getTableData');
      }
    });
  }
};

// 重定向跳转到分享页面
const skipRedirectClick = (url) => {
  let urlArr = url.split('=');
  let hash = urlArr[urlArr.length - 1];
  let routerObj = {
    hash: hash
  };
  const { href } = proxy.$router.resolve({
    path: '/enjoyLink',
    query: routerObj
  });
  window.open(href, '_blank');
};

// 编辑历史链接
const editHistoryLink = (id) => {
  let oParam = {
    id: id
  };
  ApiPerfilesShareId(oParam).then((res) => {
    let val: any = res;
    formEnjoy.shareForm = val.shareForm.toString();
    formEnjoy.password = val.password; // 生成密码
    // formEnjoy.deadline = new Date(val.deadline) || formEnjoy.deadline;
    formEnjoy.deadline = val.deadline || formEnjoy.deadline;
    formEnjoy.isPreview = val.isPreview == 1 ? ['预览'] : [];
    formEnjoy.isDownload = val.isDownload == 1 ? ['下载'] : [];
    formEnjoy.visitsNumber = val.visitsNumber != undefined ? val.visitsNumber : '';
    formEnjoy.downloadsNumber = val.downloadsNumber != undefined ? val.downloadsNumber : '';
    formEnjoy.accessibleArray = val.users != undefined ? val.users : [];
    formEnjoy.remark = val.remark;
    formEnjoy.id = val.id;
    formEnjoy.name = val.name;

    isMoreSetDiv.value = false;
    isTeamPeople.value = val.teamType;
    dialogEnjoy.value = true;
    isEnjoySuccess.value = true;
    isCreateOrEdit.value = 2;
  });
};

// 复制链接
const copyLink = (val) => {
  // let urlArr = val.split('/')
  // let url = window.document.location.origin + '/enjoyLink?hash=' + urlArr[urlArr.length-1];
  let url = val;
  //新建一个文本框
  let oInput = document.createElement('input');
  //赋值给文本框
  oInput.value = url;
  document.body.appendChild(oInput);
  // 选择对象;
  oInput.select();
  // 执行浏览器复制命令
  document.execCommand('Copy');
  //复制完成删除掉输入框
  oInput.remove();
  ElMessage.success('复制成功');
};

defineExpose({
  openDialog
});
</script>
<style scoped lang="scss">
.input-password {
  display: flex;
  align-items: center;
}

.success_link {
  margin-bottom: 8px;

  .success_title {
    margin-right: 5px;
  }
}

.success_url {
  color: #409eff;
}
</style>
